package fifteenth.Java反射机制的深入应用;

import java.lang.reflect.Array;

// 在应用中还可以通过Array类根据已有的数组类型来开辟新的数组对象
public class 修改数组的大小 {
    public static void main(String[] args) {
        int[] temp = {1, 2, 5, 7, 0};
        int newTemp[] = (int[]) arrayInc(temp, 5);// 扩大数组长度
        print(newTemp);
        System.out.println("\n-----------------");
        String[] s= {"zhangsan","lisi","wangu"};
        String ns[] = (String[]) arrayInc(s, 5);
        print(ns);
    }

    public static Object arrayInc(Object obj, int len) {// 修改数组大小
        Class<?> c = obj.getClass();
        Class<?> componentType = c.getComponentType();// 得到数组的Class对象
        Object o = Array.newInstance(componentType, len);// 重新开辟新的数组大小
        int length = Array.getLength(obj);
        System.arraycopy(obj, 0, o, 0,length);
        return o;
    }

    public static void print(Object obj) {
        Class<?> c = obj.getClass();
        if (!c.isArray()) {
            return;
        }
        Class<?> componentType = c.getComponentType();
        System.out.println(componentType.getName() + "数组的长度是：" + Array.getLength(obj));
        for (int i = 0; i < Array.getLength(obj); i++) {
            System.out.print(Array.get(obj, i) + "、");
        }
    }
}
